import { createRouter, createWebHistory } from 'vue-router'
import { checkLogin } from '../js/login.js' // 正确导入命名导出的函数

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: () => import('../views/ProgramServices/home.vue')
    },
    {
      path: '/api/login',
      name: 'login',
      component: () => import('../views/api/login.vue')
    },
    {
      path: '/crud',
      name: 'crud',
      component: () => import('../views/ProgramServices/CRUD/crud.vue')
    },
    {
      path: '/test',
      name: 'test',
      component: () => import('../views/ProgramServices/test/test.vue')
    },
  ]
})

// 设置全局守卫
router.beforeEach((to, from, next) => {
  if (to.name !== 'login') { // 如果目标路由不是登录页面
    const token = checkLogin(); // 检查登录状态
    if (token) {
      next(); // 如果有 token，允许导航继续
    } else {
      next('/api/login'); // 如果没有 token，重定向到登录页面
    }
  } else {
    next(); // 如果目标路由是登录页面，允许导航继续
  }
})

export default router
